// Workflow/ClaudeProcess/800_DEV_本地测试组件注册机制.md 的示例代码
import { LOCAL_TEST_COMPONENTS } from '@/constants/constants';

interface ComponentGroup {
  groupId?: number;
  groupName?: string;
  groupCode?: string;
  thumbnail?: string;
  subGroupList?: SubGroup[];
}

interface SubGroup {
  groupId?: number;
  groupName?: string;
  thumbnail?: string;
  componentList?: ComponentItem[];
}

interface ComponentItem {
  componentCode?: string;
  [key: string]: any;
}

const cloneSubGroup = (sub: SubGroup): SubGroup => ({
  ...sub,
  componentList: [...(sub.componentList || [])],
});

const cloneGroup = (group: ComponentGroup): ComponentGroup => ({
  ...group,
  subGroupList: (group.subGroupList || []).map(cloneSubGroup),
});

export const mergeLocalComponents = (originList: ComponentGroup[] = []): ComponentGroup[] => {
  const cloned = originList.map(cloneGroup);

  LOCAL_TEST_COMPONENTS.forEach((localGroup) => {
    const targetGroup = cloned.find(
      (group) => group.groupCode === localGroup.groupCode || group.groupName === localGroup.groupName,
    );

    if (targetGroup) {
      localGroup.subGroupList?.forEach((localSub) => {
        const targetSub = targetGroup.subGroupList?.find((sub) => sub.groupName === localSub.groupName);

        if (targetSub) {
          const existCodes = new Set((targetSub.componentList || []).map((item) => item.componentCode));
          (localSub.componentList || []).forEach((comp) => {
            if (!existCodes.has(comp.componentCode)) {
              targetSub.componentList = [...(targetSub.componentList || []), { ...comp }];
              existCodes.add(comp.componentCode);
            }
          });
        } else {
          targetGroup.subGroupList = [...(targetGroup.subGroupList || []), cloneSubGroup(localSub)];
        }
      });
    } else {
      cloned.push(cloneGroup(localGroup));
    }
  });

  return cloned;
};

export default mergeLocalComponents;
